package com.ymttest.database.mongo.config;

import java.util.List;

import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.ymttest.database.mongo.converter.YmtConverters;
import com.ymttest.utils.EnvSetup;

/**
 * Created by qianmin on 2016/12/27.
 */
@Configuration
@DependsOn("disconfMgrBean2")
public class MongoSellerConfig extends AbstractMongoConfiguration {
	private MongoClient mongo;

	@Override
	protected String getDatabaseName() {
		return SchemaField.SELLER_ORDER_INDEX;
	}

	@Override
	public MongoClient mongo() throws Exception {

		/*		System.setProperty("DEBUG.MONGO", "true");
				System.setProperty("DB.TRACE", "true");*/

		MongoClientURI uri = new MongoClientURI(
				EnvSetup.getSystemUrl("set5_mongo_sellerorderindex_uri"));
		this.mongo = new MongoClient(uri);
		return this.mongo;
	}

	@PreDestroy
	public void close() {
		if (this.mongo != null) {
			this.mongo.close();
		}
	}

	@Bean
	public MongoDbFactory mongoDbFactorySeller() throws Exception {
		return new SimpleMongoDbFactory(mongo(), SchemaField.SELLER_ORDER_INDEX);
	}

	@Bean
	public MongoTemplate mongoSellerTemplate() throws Exception {
		return new MongoTemplate(mongoDbFactorySeller(),
				mappingMongoConverter());
	}

	@Bean
	@Override
	public MappingMongoConverter mappingMongoConverter() throws Exception {
		MappingMongoConverter mmc = super.mappingMongoConverter();
		List<Converter<?, ?>> list = YmtConverters.getConvertersToRegister();

		CustomConversions customConversions = new CustomConversions(list);

		mmc.setCustomConversions(customConversions);

		mmc.afterPropertiesSet();

		return mmc;
	}
}
